<?php
// +-----------------------------------------------------------------------------------------------
// | 简易CMS
// +-----------------------------------------------------------------------------------------------
// | 后台首页
// +-----------------------------------------------------------------------------------------------
// | Author: IT果农 <htmambo@163.com> <http://www.haolie.net>
// +-----------------------------------------------------------------------------------------------
// | Version $Id$
// +-----------------------------------------------------------------------------------------------

namespace app\admin\controller;

/**
 * 后台首页控制器
 */
class Index extends AdminController {

    /**
     * 后台首页
     */
    public function index(){
        config('show_page_trace', false);
        $this->pageTitle = '管理首页';
        return $this->fetch();
    }

    public function main(){
        return $this->fetch();//exit($this->fetch());
    }
    public function getGridData(){
        exit('{"Rows":[{"CustomerID":"ALFKI","CompanyName":"Alfreds Futterkiste","ContactName":"Maria Anders","ContactTitle":"Sales Representative","Address":"Obere Str. 57","City":"Berlin","Region":null,"PostalCode":"12209","Country":"Germany","Phone":"030-0074321","Fax":"030-0076545"},{"CustomerID":"ANATR","CompanyName":"Ana Trujillo Emparedados y helados","ContactName":"Ana Trujillo","ContactTitle":"Owner","Address":"Avda. de la Constitución 2222","City":"México D.F.","Region":null,"PostalCode":"05021","Country":"Mexico","Phone":"(5) 555-4729","Fax":"(5) 555-3745"},{"CustomerID":"ANTON","CompanyName":"Antonio Moreno Taquería","ContactName":"Antonio Moreno","ContactTitle":"Owner","Address":"Mataderos  2312","City":"México D.F.","Region":null,"PostalCode":"05023","Country":"Mexico","Phone":"(5) 555-3932","Fax":null},{"CustomerID":"AROUT","CompanyName":"Around the Horn","ContactName":"Thomas Hardy","ContactTitle":"Sales Representative","Address":"120 Hanover Sq.","City":"London","Region":null,"PostalCode":"WA1 1DP","Country":"UK","Phone":"(171) 555-7788","Fax":"(171) 555-6750"},{"CustomerID":"BERGS","CompanyName":"Berglunds snabbköp","ContactName":"Christina Berglund","ContactTitle":"Order Administrator","Address":"Berguvsvägen  8","City":"Luleå","Region":null,"PostalCode":"S-958 22","Country":"Sweden","Phone":"0921-12 34 65","Fax":"0921-12 34 67"},{"CustomerID":"BLAUS","CompanyName":"Blauer See Delikatessen","ContactName":"Hanna Moos","ContactTitle":"Sales Representative","Address":"Forsterstr. 57","City":"Mannheim","Region":null,"PostalCode":"68306","Country":"Germany","Phone":"0621-08460","Fax":"0621-08924"},{"CustomerID":"BLONP","CompanyName":"Blondel père et fils","ContactName":"Frédérique Citeaux","ContactTitle":"Marketing Manager","Address":"24, place Kléber","City":"Strasbourg","Region":null,"PostalCode":"67000","Country":"France","Phone":"88.60.15.31","Fax":"88.60.15.32"},{"CustomerID":"BOLID","CompanyName":"Bólido Comidas preparadas","ContactName":"Martín Sommer","ContactTitle":"Owner","Address":"C/ Araquil, 67","City":"Madrid","Region":null,"PostalCode":"28023","Country":"Spain","Phone":"(91) 555 22 82","Fax":"(91) 555 91 99"},{"CustomerID":"BONAP","CompanyName":"Bon app\'","ContactName":"Laurence Lebihan","ContactTitle":"Owner","Address":"12, rue des Bouchers","City":"Marseille","Region":null,"PostalCode":"13008","Country":"France","Phone":"91.24.45.40","Fax":"91.24.45.41"},{"CustomerID":"BOTTM","CompanyName":"Bottom-Dollar Markets","ContactName":"Elizabeth Lincoln","ContactTitle":"Accounting Manager","Address":"23 Tsawassen Blvd.","City":"Tsawwassen","Region":"BC","PostalCode":"T2F 8M4","Country":"Canada","Phone":"(604) 555-4729","Fax":"(604) 555-3745"},{"CustomerID":"BSBEV","CompanyName":"B\'s Beverages","ContactName":"Victoria Ashworth","ContactTitle":"Sales Representative","Address":"Fauntleroy Circus","City":"London","Region":null,"PostalCode":"EC2 5NT","Country":"UK","Phone":"(171) 555-1212","Fax":null},{"CustomerID":"CACTU","CompanyName":"Cactus Comidas para llevar","ContactName":"Patricio Simpson","ContactTitle":"Sales Agent","Address":"Cerrito 333","City":"Buenos Aires","Region":null,"PostalCode":"1010","Country":"Argentina","Phone":"(1) 135-5555","Fax":"(1) 135-4892"},{"CustomerID":"CENTC","CompanyName":"Centro comercial Moctezuma","ContactName":"Francisco Chang","ContactTitle":"Marketing Manager","Address":"Sierras de Granada 9993","City":"México D.F.","Region":null,"PostalCode":"05022","Country":"Mexico","Phone":"(5) 555-3392","Fax":"(5) 555-7293"},{"CustomerID":"CHOPS","CompanyName":"Chop-suey Chinese","ContactName":"Yang Wang","ContactTitle":"Owner","Address":"Hauptstr. 29","City":"Bern","Region":null,"PostalCode":"3012","Country":"Switzerland","Phone":"0452-076545","Fax":null},{"CustomerID":"COMMI","CompanyName":"Comércio Mineiro","ContactName":"Pedro Afonso","ContactTitle":"Sales Associate","Address":"Av. dos Lusíadas, 23","City":"São Paulo","Region":"SP","PostalCode":"05432-043","Country":"Brazil","Phone":"(11) 555-7647","Fax":null},{"CustomerID":"CONSH","CompanyName":"Consolidated Holdings","ContactName":"Elizabeth Brown","ContactTitle":"Sales Representative","Address":"Berkeley Gardens\r\n12  Brewery ","City":"London","Region":null,"PostalCode":"WX1 6LT","Country":"UK","Phone":"(171) 555-2282","Fax":"(171) 555-9199"},{"CustomerID":"DRACD","CompanyName":"Drachenblut Delikatessen","ContactName":"Sven Ottlieb","ContactTitle":"Order Administrator","Address":"Walserweg 21","City":"Aachen","Region":null,"PostalCode":"52066","Country":"Germany","Phone":"0241-039123","Fax":"0241-059428"},{"CustomerID":"DUMON","CompanyName":"Du monde entier","ContactName":"Janine Labrune","ContactTitle":"Owner","Address":"67, rue des Cinquante Otages","City":"Nantes","Region":null,"PostalCode":"44000","Country":"France","Phone":"40.67.88.88","Fax":"40.67.89.89"},{"CustomerID":"EASTC","CompanyName":"Eastern Connection","ContactName":"Ann Devon","ContactTitle":"Sales Agent","Address":"35 King George","City":"London","Region":null,"PostalCode":"WX3 6FW","Country":"UK","Phone":"(171) 555-0297","Fax":"(171) 555-3373"},{"CustomerID":"ERNSH","CompanyName":"Ernst Handel","ContactName":"Roland Mendel","ContactTitle":"Sales Manager","Address":"Kirchgasse 6","City":"Graz","Region":null,"PostalCode":"8010","Country":"Austria","Phone":"7675-3425","Fax":"7675-3426"},{"CustomerID":"FAMIA","CompanyName":"Familia Arquibaldo","ContactName":"Aria Cruz","ContactTitle":"Marketing Assistant","Address":"Rua Orós, 92","City":"São Paulo","Region":"SP","PostalCode":"05442-030","Country":"Brazil","Phone":"(11) 555-9857","Fax":null},{"CustomerID":"FISSA","CompanyName":"FISSA Fabrica Inter. Salchichas S.A.","ContactName":"Diego Roel","ContactTitle":"Accounting Manager","Address":"C/ Moralzarzal, 86","City":"Madrid","Region":null,"PostalCode":"28034","Country":"Spain","Phone":"(91) 555 94 44","Fax":"(91) 555 55 93"},{"CustomerID":"FOLIG","CompanyName":"Folies gourmandes","ContactName":"Martine Rancé","ContactTitle":"Assistant Sales Agent","Address":"184, chaussée de Tournai","City":"Lille","Region":null,"PostalCode":"59000","Country":"France","Phone":"20.16.10.16","Fax":"20.16.10.17"},{"CustomerID":"FOLKO","CompanyName":"Folk och fä HB","ContactName":"Maria Larsson","ContactTitle":"Owner","Address":"Åkergatan 24","City":"Bräcke","Region":null,"PostalCode":"S-844 67","Country":"Sweden","Phone":"0695-34 67 21","Fax":null},{"CustomerID":"FRANK","CompanyName":"Frankenversand","ContactName":"Peter Franken","ContactTitle":"Marketing Manager","Address":"Berliner Platz 43","City":"München","Region":null,"PostalCode":"80805","Country":"Germany","Phone":"089-0877310","Fax":"089-0877451"},{"CustomerID":"FRANR","CompanyName":"France restauration","ContactName":"Carine Schmitt","ContactTitle":"Marketing Manager","Address":"54, rue Royale","City":"Nantes","Region":null,"PostalCode":"44000","Country":"France","Phone":"40.32.21.21","Fax":"40.32.21.20"},{"CustomerID":"FRANS","CompanyName":"Franchi S.p.A.","ContactName":"Paolo Accorti","ContactTitle":"Sales Representative","Address":"Via Monte Bianco 34","City":"Torino","Region":null,"PostalCode":"10100","Country":"Italy","Phone":"011-4988260","Fax":"011-4988261"},{"CustomerID":"FURIB","CompanyName":"Furia Bacalhau e Frutos do Mar","ContactName":"Lino Rodriguez ","ContactTitle":"Sales Manager","Address":"Jardim das rosas n. 32","City":"Lisboa","Region":null,"PostalCode":"1675","Country":"Portugal","Phone":"(1) 354-2534","Fax":"(1) 354-2535"},{"CustomerID":"GALED","CompanyName":"Galería del gastrónomo","ContactName":"Eduardo Saavedra","ContactTitle":"Marketing Manager","Address":"Rambla de Cataluña, 23","City":"Barcelona","Region":null,"PostalCode":"08022","Country":"Spain","Phone":"(93) 203 4560","Fax":"(93) 203 4561"},{"CustomerID":"GODOS","CompanyName":"Godos Cocina Típica","ContactName":"José Pedro Freyre","ContactTitle":"Sales Manager","Address":"C/ Romero, 33","City":"Sevilla","Region":null,"PostalCode":"41101","Country":"Spain","Phone":"(95) 555 82 82","Fax":null}],"total":91}');
    }
    /**
     * 给所有PHP文件加上头信息，并清除原来的头
     */
    public function Files(){
        $header = <<<str
<?php
// +-----------------------------------------------------------------------------------------------
// | 简易CMS
// +-----------------------------------------------------------------------------------------------
// | [请手动修改文件描述]
// +-----------------------------------------------------------------------------------------------
// | Author: IT果农 <htmambo@163.com> <http://www.haolie.net>
// +-----------------------------------------------------------------------------------------------
// | Version \$Id: {filename} 2 2016-09-03 07:31:55Z IT果农 <htmambo@163.com> \$
// +-----------------------------------------------------------------------------------------------


str;
        $dirs = array(
            './Addons',
            './Application'
        );

        $header = <<<str
<?php
/**
 * FILE_NAME: {filename}
 * 模块: [请修改此处]
 * 域名: work.hongshu.com
 *
 * 功能: [请修改此处]
 *
 * @copyright Copyright (c) {year} – www.hongshu.com
 * @author 果农
 * @version \$Id: {filename} {date} {time} \$
 */


str;
        $header = str_replace(array(
            '{datetime}', '{year}', '{month}', '{date}', '{time}', '{username}'
        ), array(
            date('Y-m-d H:i:s', NOW_TIME), date('Y', NOW_TIME), date('m', NOW_TIME), date('Y-m-d', NOW_TIME), date('H:i:s', NOW_TIME), session('nickname')
        ), $header);
        $dirs = array(
            '/mnt/Workarea/usr/htdocs/hongshu/workhongshu/newadmin/Application'
        );


        $files = array();
        foreach($dirs as $dir) {
            $result = \CMS\Files::listFiles($dir, '.php', true, true);
            if($result) {
                $files = array_merge($files, $result);
            }
        }
        foreach($files as $file) {
            $tmp = $lines = file($file);
            $finded = FALSE;
            $comment = false;
            foreach($tmp as $k=>$v){
                $str = trim(str_replace(array('<?php', '<?'), '', $v));
                if(!$str) {
                    $finded = true;
                    unset($lines[$k]);
                    if($comment) {
                        break;
                    }
                    continue;
                }
                $first = substr($str, 0, 2);
                if($first == '//' || $first == '/*' || substr($first, 0, 1) == '*') {
                    $comment = true;
                    unset($lines[$k]);
                    continue;
                } else {
                    break;
                }
            }
            if($finded) {
                array_unshift($lines, str_replace('{filename}', basename($file), $header));
                $content = implode("", $lines);
                file_put_contents($file, $content);
            } else {
                echo $k.':';
                echo 'File:'.$file.' Content is wrong!<br />';
                echo $v.'<br />';
                echo '<hr>';
            }
        }
    }

    public function reorder(){
        $m = model('Menu');
        $m->where('id<1000')->setInc('id', 1000);
        $m->where('pid<1000 AND pid>0')->setInc('pid', 1000);
        $lists = $m->order('pid,sort')->select();
        //$m = db('Menus');
        //$m->execute('TRUNCATE TABLE __MENUS__');
        $tree = new \CMS\Tree($lists, 'id', 'pid');
        $lists = $tree->getTree();
        $sort = 1;
        $i = 0;
        foreach($lists as $v) {
            echo $v['pre'].$v['title'].'<br />';
            if($v['id']!=$sort) {
                $data = array(
                    'id' => $sort
                );
                $map = array(
                    'id' => $v['id']
                );
                $m->where($map)->save($data);
                $map = array(
                    'pid' => $v['id']
                );
                $data = array(
                    'pid' => $sort
                );
                $m->where($map)->save($data);
                $i++;
            }
            $sort ++;
        }
        if($i) {
            echo '更新了：'.$i.'行';
        }
        $rows = $m->order('id')->select();
        pre($rows);exit;
        $m->execute('TRUNCATE TABLE __MENUS__');
        $m->addAll($rows);

    }


    /**
     * 后台用户登录
     */
    public function Login($username = null, $password = null, $verify = null){
        if(IS_POST){
            /* 检测验证码 TODO: */
            $result = check_verify($verify);
            if($result<1){
                $this->error('验证码输入错误！'. \CMS\Verify::getMsg($result));
            }
            $Member = model('Member');
            if($Member->login($username, $password)){ //登录用户
                //TODO:跳转到登录前页面
                $this->success('登录成功！', url('Index/index'));
            } else {
                $this->error($Member->getError());
            }
        } else {
            if(is_login()){
                $this->redirect('Index/index');
            }else{
                /* 读取数据库中的配置 */
                $config    =    cache('DB_CONFIG_DATA');
                if(!$config){
                    $config    =    model('Config')->lists();
                    cache('DB_CONFIG_DATA',$config);
                }
                config($config); //添加配置

                return $this->fetch('login');
            }
        }
    }

    /* 退出登录 */
    public function Logout(){
        if(is_login()){
            model('Member')->logout();
            session('[destroy]');
            $this->success('退出成功！', url('login'));
        } else {
            $this->redirect('login');
        }
    }

    public function Verify(){
        $verify = new \CMS\Verify(array('fontSize'=>25, 'length'=>5, 'imageH'=>32, 'imageW' => 150));
        $verify->entry(1);
    }

}
